#encoding=utf8
import numpy as np
import pickle
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
import os
import sys
from tqdm import tqdm

# 设置Python的递归深度以避免可能的Stack Overflow错误
sys.setrecursionlimit(2000)

#********* Begin *********#
# 此处可选填

#********* End *********#

def load_dataset(file_name):
    '''
    从文件读入数据集
    被多处调用，请勿删除或改动本函数！！！
    '''
    try:
        with open(file_name, 'rb') as f:
            raw_dataset = pickle.load(f)
    except FileNotFoundError:
        print(f"错误: 文件 {file_name} 未找到。请确保文件路径正确。")
        return None, None
        
    # 根据之前分析，pkl文件是字典格式
    # 获取第一个类别的第一张图片来确定特征维度
    try:
        example_image = raw_dataset[0][0]
    except KeyError:
        print("错误: 数据集格式不正确，无法找到类别0的数据。")
        return None, None
    except TypeError:
        print("错误: 数据集格式不正确，类别0的数据不是列表或数组。")
        return None, None

    num_classes = len(raw_dataset)
    
    dataset = np.empty((0, example_image.size))
    labels = np.empty((0, 1))

    for i_class in raw_dataset.keys():
        images_list = raw_dataset.get(i_class, [])
        if not isinstance(images_list, list) or len(images_list) == 0:
            print(f"警告：类别 {i_class} 的数据格式不正确或为空，已跳过。")
            continue
            
        for image in images_list:
            features = image.flatten()
            dataset = np.vstack((dataset, features))
            labels = np.vstack((labels, i_class))

    return dataset, labels

class Classifier:
    def __init__(self):  # 初始化模型和数据 
        self.model = None

        # 下行代码从training_dataset.pkl文件读入训练数据，得到：
        #（1）训练数据 train_dataset：形状为(1000, 784)的ndarray
        #（2）训练数据的标签 train_labels：形状为(1000, 1)的ndarray
        self.train_dataset, self.train_labels = load_dataset('./step1/input/training_dataset.pkl')
        if self.train_dataset is None:
            raise RuntimeError("训练数据集加载失败，无法继续。")

    def train(self): # 训练模型
        
        #********* BEGIN *********#
        # 使用SVC模型
        self.model = SVC(C=1.0, kernel='rbf', gamma='scale', random_state=42)
        train_labels = self.train_labels.ravel()
        self.model.fit(self.train_dataset, train_labels)  # 训练

        #********* END *********#

    def predict(self, test_dataset):  # 预测
        '''
        输入：测试数据 test_dataset: 形状为(500, 784)的ndarray
        输出：预测结果 predicted_labels: 形状为(500, )的ndarray
        '''

        #********* BEGIN *********#
        # 使用训练好的模型进行预测
        predicted_labels = self.model.predict(test_dataset)  # 预测

        #********* END *********#
        return predicted_labels
    
    #********* Begin *********#
    # 此处可选填

    #********* End *********#
    

#********* Begin *********#
# 此处可选填

#********* End *********#

def calculate_accuracy(file_name, classifier):
    test_dataset, test_labels = load_dataset(file_name)
    if test_dataset is None:
        return 0
        
    random_indices = np.random.permutation(test_dataset.shape[0])
    test_dataset = test_dataset[random_indices,:]
    test_labels = test_labels[random_indices,:]
    predicted_labels = classifier.predict(test_dataset)
    if isinstance(predicted_labels, np.ndarray):
        if predicted_labels.size != test_labels.size:
            print('错误：输出的标签数量与测试集大小不一致')
            accuracy = 0
        else:
            accuracy = np.mean(predicted_labels.flatten()==test_labels.flatten())
    else:
        print('错误：输出格式有误，必须为ndarray格式')
        accuracy = 0
    return accuracy

if __name__ == '__main__':
    classifier = Classifier()
    classifier.train()

    sum_accuracies = 0
    num_test_datasets = 0

    test_dir = './step1/input'
    
    test_files = ['test_dataset_clean.pkl'] + [
        f'test_dataset_noise_type{noise}_level{level}.pkl'
        for noise in range(1, 7)
        for level in range(1, 4)
    ]

    with tqdm(total=len(test_files), desc="正在测试", file=sys.stdout) as pbar:
        for file_name in test_files:
            file_path = os.path.join(test_dir, file_name)
            
            pbar.set_description(f"正在测试: {file_name}")

            accuracy = calculate_accuracy(file_path, classifier)

            pbar.set_postfix({'正确率': f'{accuracy:.4f}'})
            pbar.update(1)

            sum_accuracies += accuracy
            num_test_datasets += 1
    
    mean_accuracies = sum_accuracies / num_test_datasets
    print(f'你在总共{num_test_datasets}个测试集上的平均正确率为：{mean_accuracies:.4f}')
